package com.baiwei.vpnapi.service.impl;

import com.baiwei.vpnapi.dao.RecommendMapper;
import com.baiwei.vpnapi.dao.UserMapper;
import com.baiwei.vpnapi.dao.UserPackageMapper;
import com.baiwei.vpnapi.dao.VpnPackageMapper;
import com.baiwei.vpnapi.entity.UserPackage;
import com.baiwei.vpnapi.entity.VpnRecommend;
import com.baiwei.vpnapi.entity.VpnUser;
import com.baiwei.vpnapi.entity.respentity.AvailablePackage;
import com.baiwei.vpnapi.service.RecommendService;
import com.baiwei.vpnapi.utils.AppUtils;
import com.baiwei.vpnapi.utils.DateUtil;
import com.baiwei.vpnapi.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: vpnapi
 * @description:
 * @author: Mr. Stone
 * @create: 2020-09-01 18:44
 **/
@Service(value = "recService")
public class RecommendServiceImpl implements RecommendService {
    @Autowired
    private RecommendMapper recommendMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPackageMapper userPackageMapper;

    @Autowired
    private VpnPackageMapper vpnPackageMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Override
    public Object getInviteCode() {
        String token = request.getHeader("Authorization");
        VpnUser vpnUser = tokenUtil.getVpnUser(token);
        String inviteCode = vpnUser.getInviteCode();
        if(StringUtils.isEmpty(inviteCode)) {
            inviteCode = AppUtils.genInviteCode();
            QueryWrapper<VpnUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(VpnUser::getInviteCode, inviteCode);
            while (userMapper.selectOne(queryWrapper) != null) {
                inviteCode = AppUtils.genInviteCode();
                queryWrapper.lambda().eq(VpnUser::getInviteCode, inviteCode);
            }
            vpnUser.setInviteCode(inviteCode);
            userMapper.updateById(vpnUser);
            return inviteCode;
        }
        return inviteCode;
    }



    @Override
    public Object getInvitationList() {
        String token = request.getHeader("Authorization");
        VpnUser vpnUser = tokenUtil.getVpnUser(token);
        QueryWrapper<VpnRecommend> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<VpnRecommend> recLam = queryWrapper.lambda()
                .ne(VpnRecommend::getStatus, 2)
                .eq(VpnRecommend::getInviteUser, vpnUser.getUserId());
        return recommendMapper.selectList(recLam);
    }

    @Override
    public Object getInvitationTime() {
        System.out.println(vpnPackageMapper.getShareBonusPackageId());
        return getLeftInviteBonusTime();
    }

    @Override
    @Transactional
    public Object validInviteTime(Integer recId) {
        String token = request.getHeader("Authorization");
        VpnUser vpnUser = tokenUtil.getVpnUser(token);
        // 更新推荐状态 待领取 ----> 生效
        VpnRecommend recommend = recommendMapper.selectById(recId);
        if(recommend == null || recommend.getStatus() != 0){
            throw new RuntimeException("无效的分享");
        }
        recommend.setStatus(1);
        recommendMapper.updateById(recommend);

        // 如果用户没有套餐，下发低级套餐(套餐)
        AvailablePackage lastUnusedOrInusePackage =
                userPackageMapper.findLastUnusedOrInusePackage(
                        vpnUser.getUserId());
        if (lastUnusedOrInusePackage == null) {
            // 无充值套餐
            UserPackage qup = new UserPackage();
            qup.setUserId(vpnUser.getUserId());
            qup.setOrderNo("00000000000");
            long dalta = 3 * 60 * 60 * 1000;
            long nowsamp = System.currentTimeMillis();
            long endsamp = System.currentTimeMillis() + dalta;
            Date startDate = new Date(nowsamp);
            Date endDate = new Date(endsamp);
            qup.setStartTime(startDate);
            qup.setEndTime(endDate);
            qup.setStatus(1);
            qup.setPackageId(vpnPackageMapper.getShareBonusPackageId());
            userPackageMapper.insert(qup);
        } else {
            // 有充值套餐直接延长套餐时间
            UserPackage userPackage = userPackageMapper.selectById(lastUnusedOrInusePackage.getItemId());
            Date endTime = userPackage.getEndTime();
            long newEndTime = endTime.getTime() + 3 * 60 * 60 * 1000;
            endTime.setTime(newEndTime);
            userPackage.setEndTime(endTime);
            userPackageMapper.updateById(userPackage);
        }

        // 更新用户表 最近使用时间和剩余的可用推荐时间
        Integer leftBonusTime = vpnUser.getInviteBonusTime();
        Date useTime = vpnUser.getUseTime();
        if(useTime == null) {
            vpnUser.setUseTime(new Date());
            leftBonusTime = 3 * 60 * 60;
        } else {
            Integer duration = (int)((System.currentTimeMillis() - useTime.getTime())/1000);
            if(duration >= leftBonusTime) {
                vpnUser.setUseTime(new Date());
                leftBonusTime = 3 * 60 * 60;
            } else {
                leftBonusTime += 3 * 60 * 60;
            }
        }
        vpnUser.setInviteBonusTime(leftBonusTime);
        userMapper.updateById(vpnUser);
        return leftBonusTime;
    }

    // 评价奖励领取
    @Transactional
    public Object takeCommentBonus() {
        String token = request.getHeader("Authorization");
        VpnUser vpnUser = tokenUtil.getVpnUser(token);

        if(vpnUser.getEvaBonusTake().equals(1)) {
            throw new RuntimeException("已领取评价奖励");
        }
        vpnUser.setEvaBonusTake(1);
        userMapper.updateById(vpnUser);
        // 如果用户没有套餐，下发低级套餐(套餐)
        AvailablePackage lastUnusedOrInusePackage =
                userPackageMapper.findLastUnusedOrInusePackage(
                        vpnUser.getUserId());
        if (lastUnusedOrInusePackage == null) {
            // 无充值套餐
            UserPackage qup = new UserPackage();
            qup.setUserId(vpnUser.getUserId());
            qup.setOrderNo("00000000000");
            long dalta = 24 * 60 * 60 * 1000;
            long nowsamp = System.currentTimeMillis();
            long endsamp = System.currentTimeMillis() + dalta;
            Date startDate = new Date(nowsamp);
            Date endDate = new Date(endsamp);
            qup.setStartTime(startDate);
            qup.setEndTime(endDate);
            qup.setStatus(1);
            qup.setPackageId(vpnPackageMapper.getEvaBonusPackageId());
            userPackageMapper.insert(qup);
        } else {
            // 有充值套餐直接延长套餐时间
            UserPackage userPackage = userPackageMapper.selectById(lastUnusedOrInusePackage.getItemId());
            Date endTime = userPackage.getEndTime();
            long newEndTime = endTime.getTime() + 24 * 60 * 60 * 1000;
            endTime.setTime(newEndTime);
            userPackage.setEndTime(endTime);
            userPackageMapper.updateById(userPackage);
        }

        // 更新用户表 最近使用时间和剩余的可用推荐时间
        Integer leftBonusTime = vpnUser.getInviteBonusTime();
        Date useTime = vpnUser.getUseTime();
        if(useTime == null) {
            vpnUser.setUseTime(new Date());
            leftBonusTime = 24 * 60 * 60;
        } else {
            Integer duration = (int)((System.currentTimeMillis() - useTime.getTime())/1000);
            if(duration >= leftBonusTime) {
                vpnUser.setUseTime(new Date());
                leftBonusTime = 24 * 60 * 60;
            } else {
                leftBonusTime += 24 * 60 * 60;
            }
        }
        vpnUser.setInviteBonusTime(leftBonusTime);
        userMapper.updateById(vpnUser);
        return leftBonusTime;
    }

    public Integer getLeftInviteBonusTime() {
        String token = request.getHeader("Authorization");
        VpnUser vpnUser = tokenUtil.getVpnUser(token);
        Integer leftBonusTime = vpnUser.getInviteBonusTime();
        Date startUseTime = vpnUser.getUseTime();
        if(startUseTime == null) {
            return 0;
        }
        Date nowTime = new Date();
        Integer duration = DateUtil.secondsBetween(startUseTime, nowTime);
        if(duration >= leftBonusTime) {
            return 0;
        } else {
            return leftBonusTime - duration;
        }
    }
}
